<template>
  <div v-show="visible" class="poster">
    <div class="popup">
      <div class="poster-warp">
        <div id="recommend-poster">
          <img
            :src="`${backgroundImg}?x-oss-process=image/resize,m_mfit,w_750`"
            class="bgUrl"
            alt=""
          />
          <img class="bootom-img" src="@/assets/bottom-img.png" alt="" />
          <div class="poster-content">
            <!-- 海报内容 -->
            <!-- <slot></slot> -->
            <div class="content">
              <div class="info">
                <div class="name">
                  {{ shareRes.shopName }}
                </div>
                <div class="basic">
                  <img
                    v-if="shareRes.logoUrl"
                    class="head"
                    :src="shareRes.logoUrl"
                    alt=""
                  />
                  <img v-else src="@/assets/logo.png" alt="" class="head" />
                  <div
                    class="des"
                    :class="{ hasPaddingTop: !shareRes.nickname }"
                  >
                    <p class="desc">{{ shareRes.nickname }}</p>
                    <div v-if="shareRes.placardSlogan" class="specialOffer">
                      <img src="@/assets/logo.png" />
                      <p>{{ shareRes.placardSlogan }}</p>
                    </div>
                  </div>
                </div>
              </div>
              <div class="qrcode">
                <img v-if="qrcode" :src="qrcode" alt="" />
                <p class="distinguish">扫描或长按识别</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="isShow" class="posterUrl">
      <div v-if="!posterUrl" class="loading-poster">
        <!-- <div class="loading" > -->
        <!-- <van-loading /> -->
        <div class="loading-content"></div>
      </div>
      <img
        v-if="getHostEnvironment() === 'wechat' && posterUrl"
        :src="posterUrl"
        class="posterimg no-select"
        alt=""
      />
      <div
        v-if="getHostEnvironment() === 'browser' && posterUrl"
        class="posterimg"
      >
        <span>长按图片，保存至手机，方便分享和再次浏览 </span>
        <img :src="posterUrl" />
      </div>
      <img
        v-if="posterUrl"
        src="@/assets/close-btn.png"
        class="close-btn"
        alt="点击关闭"
        @click="close"
      />
    </div>
    <div class="poster-bg"></div>
  </div>
</template>
<script>
import QRCode from 'qrcode';
import html2canvas from '@/utils/html2canvas.esm';
import { getScrollY, getHostEnvironment } from '@/utils/util';
import lock from '@/utils/lock';
import shareCardMixin from '@/mixins/shareCardMixin';

export default {
  mixins: [shareCardMixin],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    shareRes: {
      type: Object,
      default: () => ({})
    },
    placardSlogan: {
      type: String,
      default: ''
    },
    backgroundImg: {
      type: String,
      default:
        'https://akmer.aikucun.com/facbd6674446b19ca9aff63d2cd9a9e151c2cbc4_1581385949978_72.png'
    }
  },
  data() {
    return {
      isShow: true,
      posterUrl: null,
      qrcode: null
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.loadAllImg();
      } else {
        this.popupClose();
        this.posterUrl = '';
        lock.beforeClose();
      }
    }
  },
  methods: {
    getHostEnvironment,
    close() {
      this.$emit('update:visible', false);
    },
    /* img加载工具方法 */
    loadImg(url) {
      return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = url;
        img.onload = () => {
          img.onload = null;
          resolve();
        };
        img.onerror = () => {
          console.error('pic加载失败===', url);
          const err = new Error('加载失败');
          reject(err);
        };
      });
    },
    // 第一步: 保证图片loading
    async loadAllImg() {
      this.resetZoom();
      const needLoadImgList = [];
      needLoadImgList.push(
        `${this.backgroundImg}?x-oss-process=image/resize,m_mfit,w_750`
      );
      needLoadImgList.push(this.shareRes.logoUrl);
      const imgsLoadArrays = needLoadImgList.map(item => this.loadImg(item));
      this.$nextTick(() => {
        Promise.all(imgsLoadArrays)
          .then(() => {
            this.createPoster();
          })
          .catch(err => {
            console.log(err);
            this.createPoster();
          });
      });
    },
    // 第二步: 海报生成
    async createPoster() {
      QRCode.toDataURL(this.shareRes.link).then(res => {
        this.qrcode = res;
        this.$nextTick(() => {
          this.createImg();
        });
      });
    },
    // 图片生成
    createImg() {
      const source = document.getElementById('recommend-poster');
      if (!source) {
        return;
      }
      const rect = source.getBoundingClientRect();
      const coptDom = source.cloneNode(true);
      coptDom.style.zIndex = -1;
      coptDom.style.width = `${rect.width}px`;
      coptDom.style.height = `${rect.height}px`;
      document.body.appendChild(coptDom);
      const scrollY = getScrollY(); // 适配iOS 13, 12 及以下 && 安卓
      console.log(scrollY);
      html2canvas(coptDom, {
        allowTaint: true,
        useCORS: true,
        x: rect.left,
        y: rect.top + scrollY,
        scale: 3,
        backgroundColor: 'transparent'
      })
        .then(canvas => {
          const imgUri = canvas.toDataURL();
          document.body.removeChild(coptDom);
          lock.afterOpen();
          this.posterUrl = imgUri;
        })
        .catch(err => {
          console.log(err);
          document.body.removeChild(coptDom);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
@keyframes mymove {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
.popup {
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: transparent;
  z-index: 9999;
  max-height: 100%;
  overflow-y: auto;
  transition: 0.3s ease-out;
  transform: translate3d(-50%, -50%, 0);
}
.loading-poster {
  width: 273px;
  height: 456px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding-left: 135px;
  .loading-content {
    width: 20px;
    height: 20px;
    border-radius: 20px;
    border-right: 1px solid #c3cbd6;
    animation: mymove 1s linear infinite;
    -webkit-animation: mymove 1s linear infinite;
  }
}
.poster-warp {
  width: 300px;
}
.posterUrl {
  top: 50%;
  left: 50%;
  position: fixed;
  width: 273px;
  transform: translate(-50%, -50%);
  z-index: 99999;
  border-radius: 8px;
  .posterimg {
    width: 273px;
    height: 456px;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    span {
      color: #ffffff;
      font-size: 12px;
      margin-bottom: 8px;
    }
    &.no-select {
      -webkit-touch-callout: none; /*系统默认菜单被禁用*/
      user-select: none; //文本不能被选择
    }
    img {
      border-radius: 8px;
      width: 100%;
    }
  }
  .close-btn {
    width: 30px;
    height: 30px;
    margin-left: 121px;
    margin-top: 30px;
  }
}
.poster-bg {
  width: 100%;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 99998;
  background-color: rgba(0, 0, 0, 0.7);
}
#recommend-poster {
  width: 273px;
  height: 500px;
  font-family: PingFang-SC-Medium;
  width: 300px;
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  overflow: hidden;
  .bgUrl {
    width: 100%;
  }
  .poster-content {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    .content {
      color: #fff;
      // background-color: #FF5107;
      width: 100%;
      position: absolute;
      top: 300px;
      box-sizing: border-box;
      padding: 10px 14px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .name {
        font-size: 14px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        margin-bottom: 13px;
        line-height: 15px;
        height: 15px;
      }
      .basic {
        display: flex;
        .des {
          &.hasPaddingTop {
            padding-top: 10px;
          }
          .desc {
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            width: 119px;
            font-size: 12px;
            color: #fff;
            // height: 22px;
            // color: #fff;
          }
          .specialOffer {
            display: flex;
            align-items: flex-start;
            justify-content: flex-start;
            border: 1px solid #feeed3;
            color: #feeed3;
            border-radius: 3px;
            padding: 2px 7px;
            min-width: 110px;
            box-sizing: border-box;
            margin-top: 4px;
            p {
              display: inline-block;
              line-height: 15px;
              max-width: 110px;
              font-size: 10px;
            }
            img {
              width: 10px;
              margin-right: 3px;
              height: auto;
            }
          }
        }
      }
      .head {
        width: 36px;
        height: 36px;
        object-fit: cover;
        margin-right: 4px;
        border-radius: 50%;
        border: 1px solid #fff;
        margin-top: 5px;
      }
      .qrcode {
        width: 76px;
        height: 76px;
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
    .distinguish {
      font-size: 10px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      margin-top: 3px;
      text-align: center;
    }
  }
  .bootom-img {
    width: 100%;
    height: auto;
  }
}
</style>
